package com.dzm.demo.myshop.web.ui.controller;

import com.dzm.demo.myshop.commons.dto.BaseResult;
import com.dzm.demo.myshop.commons.utils.EmailsSendUtils;
import com.dzm.demo.myshop.web.ui.api.UserApi;
import com.dzm.demo.myshop.web.ui.constant.SystemConstants;
import com.dzm.demo.myshop.web.ui.dto.TbUser;
import com.google.code.kaptcha.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController {

    @Autowired
    private EmailsSendUtils emailsSendUtils;

    /**
     * 跳转到登陆页
     * @return
     */
    @RequestMapping(value = "login",method = RequestMethod.GET)
    public String login(){
        return "login";
    }

    /**
     * 登陆
     * @param tbUser
     * @return
     */
    @RequestMapping(value ="login",method = RequestMethod.POST)
    public String login(TbUser tbUser, Model model, HttpServletRequest request) throws Exception {
        //验证码验证
        if (!checkVerification(tbUser,request)){
            model.addAttribute("baseResult",BaseResult.fail("验证码输入错误，请重新输入"));
            return "login";
        }

        TbUser user = UserApi.login(tbUser);
        //登陆失败
        if(user == null){
            model.addAttribute("baseResult",BaseResult.fail("用户或密码错误，请重新输入！"));
            return "login";
        }
        //登陆成功
        else{
            emailsSendUtils.send("用户登陆",String.format("用户【%s】 登陆MyShop",user.getUsername()),"849275962@qq.com");
            //将会员信息放入session
            request.getSession().setAttribute(SystemConstants.SESSION_USER_KEY,user);
            return "redirect:/index";
        }
    }

    /**
     * 注销
     * @param request
     * @return
     */
    @RequestMapping(value = "logout",method = RequestMethod.GET)
    public String logout(HttpServletRequest request){
        request.getSession().invalidate();
        return "redirect:/index";
    }

    /**
     * 检查验证码
     * @param tbUser
     * @param request
     * @return
     */
    private boolean checkVerification(TbUser tbUser,HttpServletRequest request){
        String verification = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (StringUtils.equals(verification,tbUser.getVerification())){
            return true;
        }
        return false;
    }
}
